<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
                  <a-input v-model="model.purchaseBill" placeholder="请输入单据编号"  disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="收货人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="consignee">
                  <select-user-by-dep placeholder="请选择收货人" :disabled="formDisabled" v-model="model.consignee"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="收货日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receivingDate">
                  <j-date :disabled="formDisabled" placeholder="请选择收货日期" :show-time="true" v-model="model.receivingDate" date-format="YYYY-MM-DD HH:mm" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="入库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warrantType">
                  <a-select
                    v-model="model.warrantType"
                    :disabled="formDisabled"
                    placeholder="请选择入库类型"
                    :allowClear="true"
                    @change="handleChange"
                    :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                  >
                    <a-select-option v-for="item in dataCodeList" :key="item.value" :value="item.value">{{item.text}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.warrantType === '1'">
                <a-form-model-item label="关联采购合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractId">
                  <select-purchase-contractlist-input :disabled="formDisabled" allStorage="0" v-model="model.contractId" @back="contractIdBack">
                  </select-purchase-contractlist-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.warrantType === '2'">
                <a-form-model-item label="关联采购清单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="checklistId">
                  <a-input :disabled="formDisabled" type="text" v-model="checklistId" placeholder="请选择关联采购清单" @click="checklistIdInput" :readOnly="true"></a-input>
                  <select-purchase-checklist-input-modal ref="inputModal" urlList="/api/erp/purchase/procurement/erpPurchaseChecklist/allList" :multi="true" monthDateType="1" @choseObj="choseObj"></select-purchase-checklist-input-modal>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.warrantType === '3'">
                <a-form-model-item label="关联物品领用单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialId">
                  <select-purchase-goodsreceivelist-input :disabled="formDisabled" v-model="model.materialId" @back="materialIdBack"></select-purchase-goodsreceivelist-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.warrantType === '4'">
                <a-form-model-item label="关联调拨申请单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cannibalizeId">
                  <select-purchase-cannibalizelist-input :disabled="formDisabled" v-model="model.cannibalizeId"></select-purchase-cannibalizelist-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="仓管员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storer">
                  <select-user-by-dep placeholder="请选择仓管员" :disabled="formDisabled" v-model="model.storer" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="检验员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspector">
                  <select-user-by-dep placeholder="请选择检验员" :disabled="formDisabled" v-model="model.inspector"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="入库时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warrantDate">
                  <j-date :disabled="formDisabled" placeholder="请选择入库时间" :show-time="true" v-model="model.warrantDate" date-format="YYYY-MM-DD HH:mm" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="采购单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="procurementUnit">
                  <j-select-company :disabled="formDisabled" v-model="model.procurementUnit" />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="入库明细">
            <erp-purchase-warehouse-warrant-detail-list ref="houseWarrant" :disabled="formDisabled" :storer="model.storer"
              :warrantType="model.warrantType" @checkListDel="checkListDel"/>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="purchaseFile">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.purchaseFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.purchaseFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { ajaxGetDictItems } from '@/api/api'
  import { viewFile } from '@/utils/util'
  import ViewFileModal from '@/views/scy/components/ViewFileModal'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import ErpPurchaseWarehouseWarrantDetailList from './reference/ErpPurchaseWarehouseWarrantDetailList.vue'
  import SelectPurchaseChecklistInputModal from '@/views/scy/components/modules/SelectPurchaseChecklistInputModal'
  import SelectPurchaseContractlistInput from '@/views/scy/components/SelectPurchaseContractlistInput'
  import SelectPurchaseCannibalizelistInput from '@/views/scy/components/SelectPurchaseCannibalizelistInput'
  import SelectPurchaseGoodsreceivelistInput from '@/views/scy/components/SelectPurchaseGoodsreceivelistInput'
  import { mapGetters } from 'vuex';

  export default {
    name: 'ErpPurchaseWarehouseWarrantForm',
    mixins: [viewFile],
    components: {
      ViewFileModal,
      SelectUserByDep,
      ErpPurchaseWarehouseWarrantDetailList,
      SelectPurchaseChecklistInputModal,
      SelectPurchaseContractlistInput,
      SelectPurchaseCannibalizelistInput,
      SelectPurchaseGoodsreceivelistInput
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
          purchaseBill: null,
          checklistId: null,
          checklistName: null
        },
        activeKey: ['1','2','3'],
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          consignee: [
              { required: true, message: '请选择收货人!', trigger: 'change'},
          ],
          receivingDate: [
              { required: true, message: '请选择收货日期!', trigger: 'change'},
          ],
          warrantType: [
              { required: true, message: '请选择入库类型!', trigger: 'blur'},
          ],
          storer: [
              { required: true, message: '请选择仓管员!', trigger: 'change'},
          ],
          inspector: [
              { required: true, message: '请选择检验员!', trigger: 'change'},
          ],
          warrantDate: [
              { required: true, message: '请选择入库时间!', trigger: 'change'},
          ],
          companName: [
              { required: true, message: '请选择供应商名称!', trigger: 'change'},
          ],
          // procurementUnit: [
          //     { required: true, message: '请选择采购单位!', trigger: 'change'},
          // ],
        },
        url: {
          add: "/api/erp/purchase/storehouse/erpPurchaseWarehouseWarrant/add",
          edit: "/api/erp/purchase/storehouse/erpPurchaseWarehouseWarrant/edit",
          queryById: "/api/erp/purchase/storehouse/erpPurchaseWarehouseWarrant/queryById",
          gainBillNo: "/api/erp/purchase/storehouse/erpPurchaseWarehouseWarrant/gainBillNo",
          contractIdList: '/api/erp/purchase/contract/erpPurchaseContractSupplies/allListTo',
          materialIdList: '/api/erp/purchase/recipients/erpPurchaseRecipientsDetail/allList'
        },
        dataCodeList: [],
        checklistId: null,
        selectedObj: [],
        ids: []
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      ...mapGetters(['userInfo']),
      getBillNo () {
        const that = this
        getAction(this.url.gainBillNo).then((res)=>{
          if(res.success){
            that.model.purchaseBill = res.result//单据编号
          }
        })
      },
      findDataCodeList() {
        ajaxGetDictItems('warrant_type').then(res => {
          if (res.success) {
            this.dataCodeList = res.result
          }
        })
      },
      handleChange(value) {
        this.$set(this.model, 'checklistId', null)
        this.$set(this.model, 'cannibalizeId', null)
        this.$set(this.model, 'contractId', null)
        this.$set(this.model, 'materialId', null)
        this.checklistId = null
        if(value === '1'){
          this.$refs.form.clearValidate('checklistId');
          this.$refs.form.clearValidate('materialId');
          this.$refs.form.clearValidate('cannibalizeId');
          this.$set(this.validatorRules, 'contractId', [
            { required: true, message: '请选择关联采购合同!', trigger: 'change'},
          ])
        }
        if(value === '2'){
          this.$refs.form.clearValidate('contractId');
          this.$refs.form.clearValidate('materialId');
          this.$refs.form.clearValidate('cannibalizeId');
          this.$set(this.validatorRules, 'checklistId', [
            { required: true, message: '请选择关联采购清单!', trigger: 'blur'},
          ])
        }
        if(value === '3'){
          this.$refs.form.clearValidate('contractId');
          this.$refs.form.clearValidate('checklistId');
          this.$refs.form.clearValidate('cannibalizeId');
          this.$set(this.validatorRules, 'materialId', [
            { required: true, message: '请选择关联物品领用单!', trigger: 'blur'},
          ])
        }
        if(value === '4'){
          this.$refs.form.clearValidate('checklistId');
          this.$refs.form.clearValidate('materialId');
          this.$refs.form.clearValidate('contractId');
          this.$set(this.validatorRules, 'cannibalizeId', [
            { required: true, message: '请选择关联调拨申请单!', trigger: 'change'},
          ])
        }
        //其他
        if(value === '5'){
          this.$refs.houseWarrant.addFlag = true
        } else {
          this.$refs.houseWarrant.addFlag = false
        }
        this.$refs.houseWarrant.dataSource = []
        this.$refs.houseWarrant.handleChangeWarrantType(value)
      },
      add () {
        this.edit(this.modelDefault);
        this.getBillNo()
        this.model.storer = this.userInfo().empId; //仓管员
        this.selectedObj = []
        this.ids = []
      },
      edit (record) {
        this.findDataCodeList()
        this.$refs["form"].clearValidate();
        this.model = Object.assign({}, record);
        if (this.model.id) {
          this.$refs.houseWarrant.loadData(1, this.model.id)
        } else {
          this.$refs.houseWarrant.dataSource = []
        }
        //判断是否关联采购清单
        if(!!this.model.checklistId) {
          this.selectedObj = [];
          this.ids = this.model.checklistId.split(',');
          let url = '';
          let param = {};
          if (this.ids.length == 1) {
            url = '/api/erp/purchase/procurement/erpPurchaseChecklist/queryById';
            param = { id: this.model.checklistId };
          } else {
            url = '/api/erp/purchase/procurement/erpPurchaseChecklist/queryByIds';
            param = { ids: this.model.checklistId };
          }
          if(!!this.model.id) {
            param.warrantId = this.model.id
          }
          getAction(url, param).then((res) => {
            if (res.success) {
              if (!Array.isArray(res.result)) {
                this.selectedObj.push(res.result);
              } else {
                for (let i = 0; i < res.result.length; i++) {
                  this.selectedObj.push(res.result[i]);
                }
              }
            }
          });
        }
        //其他
        if(this.model.warrantType == 5){
          this.$refs.houseWarrant.addFlag = true
        } else {
          this.$refs.houseWarrant.addFlag = false
        }
        if(!!this.model.warrantType) {
          this.$refs.houseWarrant.handleChangeWarrantType(this.model.warrantType)
        } else {
          this.$refs.houseWarrant.handleChangeWarrantType()
        }
        if(this.model.warrantType === '2' && !!this.model.checklistName){
          this.checklistId = this.model.checklistName
          this.$set(this.validatorRules, 'checklistId', [
            { required: true, message: '请选择关联采购清单!', trigger: 'blur'},
          ])
        } else {
          this.checklistId = null
        }
        this.visible = true;
      },
      submitForm () {
        let details = this.$refs.houseWarrant.submitForm()
        if(!details.length > 0) {
          this.$message.warning('请添加入库明细信息！');
          this.$emit('unButtonDisable');
          return
        }

        if (this.model.warrantType == 5) {
          // 判断数据有没有填写送货数量、退回数量、存放仓库
          var isDeliveryNum = details.some(item => !item.deliveryNum);
          var isReturnNum = details.some(item => item.returnNum === '' || item.returnNum === null);
          var isStorehouseId = details.some(item => !item.storehouseId);

          if (isDeliveryNum) {
            // 当为true说明有值送货数量没有填写
            this.$message.warning('请填写入库明细中的送货数量！');
            this.$emit('unButtonDisable');
            return false
          }
          if (isReturnNum) {
            // 当为true说明退回数量没有填写
            this.$message.warning('请填写物料明细中的退回数量！');
            this.$emit('unButtonDisable');
            return false
          }
          if (isStorehouseId) {
            // 当为true说明存放仓库没有填写
            this.$message.warning('请选择物料明细中的存放仓库！');
            this.$emit('unButtonDisable');
            return false
          }

          for (let index = 0; index < details.length; index++) {
            // 判断当填写有效期时，需要填写有效期单位
            const element = details[index];
            console.log('00000element', element)
            if (element.periodValidity) {
              if (!element.periodValidityUnit) {
                this.$message.warning(`请选择物料明细中第${index + 1}个的有效期单位！`);
                this.$emit('unButtonDisable');
                return false
              }
            }
          }
        }

        //合同类或者非合同类 或 退库类
        if(this.model.warrantType == 1 || this.model.warrantType == 2 || this.model.warrantType == 3) {
          //循环判断子表数据是否完善
          for (let index = 0; index < details.length; index++) {
            const element = details[index];
            if(this.model.warrantType == 1 || this.model.warrantType == 2) {
              if(isNaN(element.purchaseNum) || isNaN(element.warrantAmount) || isNaN(element.deliveryNum) || isNaN(element.returnNum) || isNaN(element.warrantNum) || !element.storehouseId) {
                this.$message.warning('请完善入库明细信息中的必填项！');
                this.$emit('unButtonDisable');
                return
              }
            } else if(this.model.warrantType == 3) {
              if(isNaN(element.purchaseNum) || isNaN(element.deliveryNum) || isNaN(element.returnNum) || isNaN(element.warrantNum) || !element.storehouseId) {
              this.$message.warning('请完善入库明细信息中的必填项！');
              this.$emit('unButtonDisable');
              return
            }
            }
          }
        }
        if(this.model.warrantType === '2' && !!this.checklistId){
          this.$set(this.model, 'checklistName', this.checklistId)
        } else {
          this.$set(this.model, 'checklistName', null)
        }
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            this.model.detailList = details
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              that.$emit('unButtonDisable');
              }
            }).catch((error)=>{
              that.$emit('unButtonDisable');
            }).finally(() => {
              that.confirmLoading = false;
            })
          } else {
            that.$emit('unButtonDisable');
          }

        })
      },
      // 关联采购申请单子modal回调
      choseObj(list) {
        this.selectedObj = list;
        this.ids = [];
        let contractDataSource = []
        for (var i = 0; i < list.length; i++) {
          this.ids.push(list[i].id);
          //子表数据
          let dataOne = {}
          dataOne.provisionBroad = list[i].provisionBroad//物料大类
          dataOne.provisionSmall = list[i].provisionSmall//物料小类
          dataOne.materialBillId = list[i].materialBillId//物料编号
          dataOne.materialName = list[i].materialName//物料名称
          dataOne.specification = list[i].specification//规格型号
          dataOne.unit = list[i].unit//单位
          dataOne.brand = list[i].brand//品牌
          dataOne.purchaseNum = list[i].amount//采购数量
          dataOne.warrantAmount = list[i].warrantAmount//累计入库数量
          dataOne.childId = list[i].id//关联子表id
          contractDataSource.push(dataOne)
        }
        let objs = this.ids.join(',');
        this.model.checklistId = objs
        if(list.length > 0) {
          let details = this.$refs.houseWarrant.submitForm()
          contractDataSource.forEach(element => {
            let index = details.findIndex((item) => item.childId == element.childId);
            //设置子表数据
            if(index < 0) {
              this.$refs.houseWarrant.dataOne(element, true)
            }
          });
          details = this.$refs.houseWarrant.submitForm()
          for (var i = 0; i < details.length; i++) {
            let index = contractDataSource.findIndex((item) => item.childId == details[i].childId);
            if (index < 0) {
              this.$refs.houseWarrant.dataSource.splice(i, 1);
            }
          }
          this.$refs.houseWarrant.dataSource.forEach((item, index) => {
            item.key = index
          })
          details = this.$refs.houseWarrant.submitForm()
          this.checklistId = list[0].monthDate + '采购清单'
          this.$refs.form.clearValidate('checklistId');
        } else {
          this.checklistId = null
          this.$refs.houseWarrant.dataSource = []
          this.$refs.form.validateField('checklistId', (Error) => {
            if (!Error) {
              return true
            } else {
              return false
            }
          })
        }
      },
      checklistIdInput(){
        if(this.ids.length == 0) {
          this.selectedObj = []
          this.$refs.inputModal.monthDateFlag = false
          this.$refs.inputModal.searchReset(1)
        }
        this.$refs.inputModal.add(this.selectedObj, this.ids);
      },
      //采购合同
      contractIdBack(value) {
        if(value.length > 0) {
          let contractDataSource = []
          const that = this;
          let parem = { billId: value[0].id}
          if(!!this.model.id) {
            parem.warrantId = this.model.id
          }
          getAction(this.url.contractIdList, parem).then(res => {
            if (res.success) {
              //设置子表数据
              for (var i = 0; i < res.result.length; i++) {
                let element = res.result[i]
                let dataOne = {}
                dataOne.key = i
                dataOne.provisionBroad = element.provisionBroad//物料大类
                dataOne.provisionSmall = element.provisionSmall//物料小类
                dataOne.materialBillId = element.materialBillId//物料编号
                dataOne.materialName = element.materialName//物料名称
                dataOne.specification = element.specification//规格型号
                dataOne.unit = element.unit//单位
                dataOne.brand = element.brand//品牌
                dataOne.companName = value[0].supplyCompanName//供应商
                dataOne.purchaseNum = element.amount//采购数量
                dataOne.warrantAmount = element.warrantAmount//累计入库数量
                dataOne.childId = element.id//关联子表id
                contractDataSource.push(dataOne)
              }
              that.$refs.houseWarrant.dataSource = contractDataSource
            }else{
              that.$message.warning(res.message);
            }
          })
        }
      },
      materialIdBack(value) {
        if(value.length > 0) {
          let materialDataSource = []
          const that = this;
          getAction(this.url.materialIdList, { billId: value[0].id}).then(res => {
            if (res.success) {
              //设置子表数据
              for (var i = 0; i < res.result.length; i++) {
                let element = res.result[i]
                let dataOne = {}
                dataOne.key = i
                dataOne.provisionBroad = element.provisionBroad//物料大类
                dataOne.provisionSmall = element.provisionSmall//物料小类
                dataOne.materialBillId = element.materialBillId//物料编号
                dataOne.materialName = element.materialName//物料名称
                dataOne.specification = element.specification//规格型号
                dataOne.unit = element.unit//单位
                dataOne.brand = element.brand//品牌
                dataOne.companName = element.companName//供应商
                dataOne.purchaseNum = element.recipientsNum//领用数量
                dataOne.childId = element.id//关联子表id
                materialDataSource.push(dataOne)
              }
              that.$refs.houseWarrant.dataSource = materialDataSource
            }else{
              that.$message.warning(res.message);
            }
          })
        }
      },
      checkListDel(data) {
        let indexSelectedObj = this.selectedObj.findIndex((item) => item.id == data.childId);
        let indexIds = this.ids.indexOf(data.childId)
        this.selectedObj.splice(indexSelectedObj, 1);
        this.ids.splice(indexIds, 1);
        if(this.selectedObj.length == 0 && this.ids.length == 0) {
          this.checklistId = null
          this.$set(this.model, 'checklistName', null)
          this.$refs.form.validateField('checklistId', (Error) => {
            if (!Error) {
              return true
            } else {
              return false
            }
          })
        }
      }
    }
  }
</script>
